<?php
/**
 * 维修记录审批表
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/5/31
 * Time: 16:47
 * Mail: hjklrchang@qq.com
 */

namespace app\adminapi\model;

use app\adminapi\filter\MaintenanceApproveFilter;
use app\base\exception\ParamException;
use app\base\exception\RecordNotFoundException;
use traits\model\SoftDelete;

class MaintenanceApprove extends  Common {
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    protected $type = [
        'material_cost_info' => 'array',
        'working_hours' => 'array',
    ];

    /**
     * 获取维修记录审批列表
     * @param $where
     * @param $fields
     * @param int $page
     * @param int $pagenum
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function listData($where, $fields, $page = 1, $pagenum = 20) {
        $filter = new MaintenanceApproveFilter($fields, $where);
        $condition = $filter->geFiltered();
        $where = $condition['where'];
        $fields = $condition['field'];
        $mark = $filter->getMark();

        $buildQuery = function($query) use ($where) {
            self::authCompanyQuery($query, $where, 'company_id');
        };

        $result = [];
        $result['count'] = $this->where($buildQuery)->count();
        $result['list'] = $this->where($buildQuery)
            ->page($page, $pagenum)
            ->field($fields)
            ->order('approve_id desc')
            ->select();

        return array_merge($result, $mark);
    }

    /**
     * 新增或者编辑维修记录审批
     * @param $params
     * @return $this|false|int
     * @throws ParamException
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrUpdate($params) {
        $session = (new User())->getLoginUser();
        if(isset($params['approve_id'])) {
            $where = ['approve_id' => $params['approve_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'company_id');
            };
            $approve = self::get($buildQuery);
            if(!$approve) {
                throw new RecordNotFoundException();
            }
        }elseif(!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        // 更新时记录审核通过时间
        if(isset($params['approve_id']) && $approve->getAttr('approve_status') !== $params['approve_status'] && in_array($params['approve_status'], ['3', '4'])) {
            $params['approve_time'] = date('Y-m-d H:i:s');
        }

        // 总维修费用
        $params['maintenance_total'] = $params['material_cost_total'] + $params['working_hours_total'];

        // 补全关联字段
        $record = $this->addRelativeFields( $params, 'app\adminapi\model\MaintenanceRecord', $params['maintenance_record_id'],  ['car_id'], '关联维修记录不存在');
        if(!$record->getAttr('car_id')) {
            throw new ParamException('关联维修记录中的card_id不能为空');
        }
        $car = $this->addRelativeFields( $params, 'app\adminapi\model\Car', $params['car_id'],  ['number'=>'plate_no'], '关联车辆不存在');
        $company = $this->addRelativeFields( $params, 'app\adminapi\model\Company', $params['company_id'],  ['company_name'], '关联单位不存在');
        $maintenance = $this->addRelativeFields( $params, 'app\adminapi\model\Maintenance',$params['maintenance_id'], ['maintenance_name'],'关联维修厂不存在');

        if(isset($params['approve_id'])) {
            return $this->isUpdate(true)->save($params);
        }

        // 新增时记录审核通过时间
        if( in_array($params['approve_status'], ['3', '4']) ) {
            $params['approve_time'] = date('Y-m-d H:i:s');
        }

        $oldRecord = $this->where(['maintenance_record_id' => $params['maintenance_record_id']])->find();
        if($oldRecord){
            throw new ParamException('当前维修记录已经添加过审核，不能继续提交审核');
        }

        $this->save($params);
        return $this;
    }

}